<?php

namespace Biz\service\brand;

use Biz\cache\brand\BrandBeLikedache;
use Biz\model\brand\BrandHhzCard as mBrandHhzCard;
use Biz\model\brand\BrandLink as mBrandLink;
use Biz\model\wiki\WikiRankingBrand;
use Biz\pockets\serviceTrait\_Async;
use Doraemon\cache\UserCounter;
use Doraemon\model\ImageCreate\ImageCreate as mImageCreate;
use Doraemon\tools\ImageCreate;
use Doraemon\tools\Log;

/**
 * 品牌名片
 * Class BrandHhzCard
 * @package Biz\service\brand
 */
class BrandHhzCard
{
    use _Async;

    public static function getTemplateList($brandId, $uid)
    {
        $userCounter = self::getUserCounter($brandId, $uid);
        $brandInfo = Brand::getBrandInfo4App($brandId);
        $qrCodeLink = self::getBrandHomeLink($brandId);
        $brandCardList = mBrandHhzCard::selectList(['brand_id' => $brandId]);
        $brandCardList = array_column($brandCardList, null, 'template');
        $list = [];
        foreach (mBrandHhzCard::TEMPLATE_DESC as $template => $desc) {
            $brandCardInfo = isset($brandCardList[$template]) ? $brandCardList[$template] : [];
            $cardImg = $brandCardInfo['card_img'] ? json_decode($brandCardInfo['card_img'], true) : [];
            $cardImg = self::formatCardImgs($template, $cardImg);
            $bigImg = '';
            $guideDesc = '';
            $showContentNum = 1;
            $title = '';
            $description = '';
            if ($brandCardInfo) {
                $bigImg = $brandCardInfo['bg_img'];
                $guideDesc = $brandCardInfo['guide_desc'];
                $showContentNum = $brandCardInfo['show_content_num'];
            }

            if ($template == mBrandHhzCard::TEMPLATE_RANK_HONORS_YEAR) {
                $title = self::getLastYearTitle();
                $description = self::getAwardDescByDate($brandId, self::getLastYearSection());
            }
            if ($template == mBrandHhzCard::TEMPLATE_RANK_HONORS_QUARTER) {
                $title = self::getLastQuarterTitle();
                $description = self::getAwardDescByDate($brandId, self::getLastQuarterSection());
            }
            $list[] = [
                'template' => $template,
                'brand_name' => $brandInfo['name'],
                'logo' => $brandInfo['logo'],
                'counter' => $userCounter,
                'link' => $qrCodeLink,
                'bg_img' => $bigImg,
                'guide_desc' => $guideDesc,
                'show_content_num' => $showContentNum,
                'desc' => $desc,
                'has_card_img' => empty($brandCardInfo['card_img']) ? 0 : 1,
                'card_img' => $cardImg,
                'title' => $title,
                'description' => $description,
            ];
        }

        return $list;
    }

    public static function getUserCounter($brandId, $uid)
    {
        $userLike = BrandBeLikedache::getUserLike($brandId);
        $userCounter = UserCounter::getOne($uid);
        $beLiked = $userCounter['beliked'] ? $userCounter['beliked'] : 0;
        $beFavorited = $userCounter['befavorited'] ? $userCounter['befavorited'] : 0;
        $userLike = $userLike + $beLiked + $beFavorited;

        return [
            'befavorited' => $beFavorited,
            'user_like' => $userLike,
            'liver_said' => $userCounter['liver_said'] ? $userCounter['liver_said'] : 0,
            'fans' => $userCounter['fans'] ? $userCounter['fans'] : 0,
        ];
    }

    public static function getBrandHomeLink($brandId, $brandUid = 0)
    {
        $info = mBrandLink::getInfo(['brand_id' => $brandId]);
        $shorLink = $info ? $info['short_link'] : '';
        if (empty($shorLink) && $brandId && $brandUid) {
            $shorLink = mBrandLink::createShortLink($brandId, $brandUid);
        }
        $qrCodeLink = $shorLink ? mBrandLink::SHORT_PREFIX.$shorLink : '';

        return $qrCodeLink;
    }

    private static function formatCardImgs($template, array $cardImg)
    {
        $result = [];
        $cardImgKeys = array_keys(mBrandHhzCard::TEMPLATE_CARD_SIZE[$template]);
        foreach ($cardImgKeys as $id) {
            if (isset($cardImg[$id])) {
                $result[] = [
                    'id' => $id,
                    'img' => $cardImg[$id],
                ];
            } else {
                $result[] = [
                    'id' => $id,
                    'img' => '',
                ];
            }
        }

        return $result;
    }

    /**
     * 获取年度上榜标题
     * @return string
     */
    public static function getLastYearTitle(): string
    {
        $lastYear = date('Y', strtotime('-1 year'));

        return $lastYear.'年度';

    }

    /**
     * 获取品牌上榜次数
     * @param $brandId
     * @param array $date
     * @return string
     */
    public static function getAwardDescByDate($brandId, array $date): string
    {
        $map = [
            'AND' => [
                'brand_id' => $brandId,
                'ranking_day[<>]' => $date,
                'ranking_state' => WikiRankingBrand::RANKING_STATE_SHOW,
            ],
        ];
        $awardCount = WikiRankingBrand::getCount($map) ?? 0;

        return '累计第'.$awardCount.'次上榜';
    }

    /**
     * 获取去年年度时间区间
     * @return string[]
     */
    public static function getLastYearSection(): array
    {
        $LastYear = date('Y', strtotime('-1 year'));

        return [$LastYear.'0101', $LastYear.'1231'];
    }

    /**
     * 获取季度上榜标题
     */
    public static function getLastQuarterTitle(): string
    {
        $year = date('Y');
        $quarterMap = [1 => '一', 2 => '二', 3 => '三', 4 => '四'];
        $season = ceil((date('n')) / 3) - 1;

        return $year.'第'.$quarterMap[$season].'季度';

    }

    /**
     * 获取上个季度时间区间
     * @return array
     */
    public static function getLastQuarterSection(): array
    {
        $season = ceil((date('n')) / 3) - 1;//上季度是第几季度

        return [
            date('Ymd', mktime(0, 0, 0, $season * 3 - 3 + 1, 1, date('Y'))),
            date('Ymd',
                mktime(23, 59, 59, $season * 3, date('t', mktime(0, 0, 0, $season * 3, 1, date("Y"))), date('Y'))),
        ];
    }

    public static function getTemplateInfo($template, $brandId, $uid)
    {
        $brandCardInfo = mBrandHhzCard::get(['brand_id' => $brandId, 'template' => $template]);
        $userCounter = self::getUserCounter($brandId, $uid);
        $brandInfo = Brand::getBrandInfo4App($brandId);
        $qrCodeLink = self::getBrandHomeLink($brandId);
        $info = [
            'template' => $template,
            'brand_name' => $brandInfo['name'],
            'logo' => $brandInfo['logo'],
            'counter' => $userCounter,
            'link' => $qrCodeLink,
            'bg_img' => ($brandCardInfo && $brandCardInfo['bg_img']) ? $brandCardInfo['bg_img'] : '',
            'guide_desc' => ($brandCardInfo && $brandCardInfo['guide_desc']) ? $brandCardInfo['guide_desc'] : '',
            'show_content_num' => ($brandCardInfo && $brandCardInfo['show_content_num']) ? $brandCardInfo['show_content_num'] : 1,
        ];

        return $info;
    }

    public static function save($brandId, $uid, $params)
    {
        $template = $params['template'];
        $where = [
            'brand_id' => $brandId,
            'template' => $template,
        ];
        $params['card_img'] = '';
        $info = mBrandHhzCard::getInfo($where);
        if ($info) {
            $result = mBrandHhzCard::updateData($params, $where);
        } else {
            $params['brand_id'] = $brandId;
            $result = mBrandHhzCard::insertData($params);
        }
        if (!$result) {
            return false;
        }

        $userCounter = self::getUserCounter($brandId, $uid);
        $brandInfo = Brand::getBrandInfo4App($brandId);
        $qrCodeLink = self::getBrandHomeLink($brandId, $uid);

        $createData = [
            'tid' => 0,
            'params' => [],
            'size' => [],
        ];
        switch ($template) {
            case mBrandHhzCard::TEMPLATE_ONE://竖版1
                $liverSaid = '';
                if ($params['show_content_num']) {
                    if ($userCounter['liver_said'] >= 9990000) {
                        $liverSaid = '999W+';
                    } else {
                        if ($userCounter['liver_said'] >= 10000) {
                            $liverSaid = sprintf("%.1f", $userCounter['liver_said'] / 10000).'W';
                        } else {
                            $liverSaid = $userCounter['liver_said'];
                        }
                    }
                    $liverSaid = ($liverSaid ? $liverSaid : 0).'条住友真实晒图';
                }

                if ($userCounter['fans'] >= 9990000) {
                    $fans = '999W+';
                } else {
                    if ($userCounter['fans'] >= 10000) {
                        $fans = sprintf("%.1f", $userCounter['befavorited'] / 10000).'W';
                    } else {
                        $fans = $userCounter['fans'];
                    }
                }
                $fans = (string)($fans ? $fans : 0).'被关注';


                if ($userCounter['user_like'] >= 9990000) {
                    $userLike = '999W+';
                } else {
                    if ($userCounter['user_like'] >= 10000) {
                        $userLike = sprintf("%.1f", $userCounter['user_like'] / 10000).'W';
                    } else {
                        $userLike = $userCounter['user_like'];
                    }
                }
                $userLike = (string)($userLike ? $userLike : 0).'住友喜爱';

                $createData['params'] = [
                    'https://img.haohaozhu.cn/Op-imageShow/1610a30va18g0Ja00qmx1in?iv=1',//背景图
                    $brandInfo['logo'],//品牌logo
                    $brandInfo['name'],//品牌名
                    $liverSaid,//文案一
                    $fans.' '.$userLike,//文案二
                    $qrCodeLink,//二维码
                    $params['guide_desc'],//二维码下面的描述
                ];
                break;
            case mBrandHhzCard::TEMPLATE_TWO://竖版2
                $liverSaid = '';
                $liverSaidDesc = '';
                if ($params['show_content_num']) {
                    if ($userCounter['liver_said'] >= 9990000) {
                        $liverSaid = '999W+';
                    } else {
                        if ($userCounter['liver_said'] >= 10000) {
                            $liverSaid = sprintf("%.1f", $userCounter['liver_said'] / 10000).'W';
                        } else {
                            $liverSaid = $userCounter['liver_said'];
                        }
                    }
                    $liverSaid = (string)($liverSaid ? $liverSaid : 0);
                    $liverSaidDesc = '位住友分享了Ta在家里的样子';
                }

                if ($userCounter['user_like'] >= 9990000) {
                    $userLike = '999W+';
                } else {
                    if ($userCounter['user_like'] >= 10000) {
                        $userLike = sprintf("%.1f", $userCounter['user_like'] / 10000).'W';
                    } else {
                        $userLike = $userCounter['user_like'];
                    }
                }
                $bigImg = $params['bg_img'] ? $params['bg_img'] : 'https://img.haohaozhu.cn/Op-imageShow/f2c2830va0gz08B00qmx6xq?iv=1';
                $createData['params'] = [
                    'https://img.haohaozhu.cn/Op-imageShow/72c9130va18g0cC00qmx6q0?iv=1',//背景图
                    $bigImg,//背景图上
                    'https://img.haohaozhu.cn/Op-imageShow/424c930va0gw0mA00qn9svt?iv=1',//背景图上蒙版
                    'https://img.haohaozhu.cn/Op-imageShow/e1f2730va18g0kl00qn67k0?iv=1',//浮图
                    $brandInfo['logo'],//品牌logo
                    $brandInfo['name'],//品牌名
                    $qrCodeLink,//二维码
                    $params['guide_desc'],//二维码下面的描述
                    (string)($userLike ? $userLike : 0),//住友喜欢数
                    $liverSaid,//嗮单数
                    $liverSaidDesc,//嗮单数文案
                ];
                break;
            case mBrandHhzCard::TEMPLATE_THREE://横版
                $liverSaid = '';
                $liverSaidDesc = '';
                if ($params['show_content_num']) {
                    if ($userCounter['liver_said'] >= 9990000) {
                        $liverSaid = '999W+';
                    } else {
                        if ($userCounter['liver_said'] >= 10000) {
                            $liverSaid = sprintf("%.1f", $userCounter['liver_said'] / 10000).'W';
                        } else {
                            $liverSaid = $userCounter['liver_said'];
                        }
                    }
                    $liverSaid = (string)($liverSaid ? $liverSaid : 0);
                    $liverSaidDesc = '位住友分享了Ta在家里的样子';
                }

                if ($userCounter['user_like'] >= 9990000) {
                    $userLike = '999W+';
                } else {
                    if ($userCounter['user_like'] >= 10000) {
                        $userLike = sprintf("%.1f", $userCounter['user_like'] / 10000).'W';
                    } else {
                        $userLike = $userCounter['user_like'];
                    }
                }
                $bigImg = $params['bg_img'] ? $params['bg_img'] : 'https://img.haohaozhu.cn/Op-imageShow/f2c2830va0gz08B00qmx6xq?iv=1';
                $createData['params'] = [
                    'https://img.haohaozhu.cn/Op-imageShow/66eeb30bl0m10NT00qn8b3p?iv=1',//背景图右蒙版
                    $bigImg,//背景图左
                    'https://img.haohaozhu.cn/Op-imageShow/025e530jq0m10iv00qn9sd2?iv=1',//背景图左蒙版
                    'https://img.haohaozhu.cn/Op-imageShow/ef3fd30vb0m10v000qn9s78?iv=1',//浮图
                    $brandInfo['logo'],//品牌logo
                    $brandInfo['name'],//品牌名
                    $qrCodeLink,//二维码
                    $params['guide_desc'],//二维码下面的描述
                    (string)($userLike ? $userLike : 0),//住友喜欢数
                    $liverSaid,//嗮单数
                    $liverSaidDesc,//嗮单数文案
                ];
                break;
            case mBrandHhzCard::TEMPLATE_RANK_HONORS_YEAR://榜单荣誉-年度
                $lastYearTitle = self::getLastYearTitle();
                $awardDesc = self::getAwardDescByDate($brandId, self::getLastYearSection());
                $createData['params'] = [
                    'https://img.haohaozhu.cn/Biz-imageShow/cb78b314n1lr0Xf00rl2tln?iv=1',//背景图
                    'https://img.haohaozhu.cn/Biz-imageShow/968be30gy0gy0bw00rl44nx?iv=1',//品牌logo背景图
                    $brandInfo['logo'],//品牌logo
                    'https://img.haohaozhu.cn/Biz-imageShow/2855230ut03f0oh00rl2u5p?iv=1',//品牌名称背景图
                    $brandInfo['name'],//品牌名称
                    $lastYearTitle,//年度上榜标题
                    $awardDesc,//年度上榜次数
                    $qrCodeLink,//品牌主页二维码
                    $params['guide_desc'],//二维码旁边的描述
                ];
                break;
            case mBrandHhzCard::TEMPLATE_RANK_HONORS_QUARTER://榜单荣誉-季度
                $lastQuarterTitle = self::getLastQuarterTitle();
                $awardDesc = self::getAwardDescByDate($brandId, self::getLastQuarterSection());
                $createData['params'] = [
                    'https://img.haohaozhu.cn/Biz-imageShow/7cffc314n1lq0DX00rl49tw?iv=1',//背景图
                    'https://img.haohaozhu.cn/Biz-imageShow/75be430gw0gv0yN00rl49yf?iv=1',//品牌logo背景图
                    $brandInfo['logo'],//品牌logo
                    'https://img.haohaozhu.cn/Biz-imageShow/5374930ut03f06V00rl49wp?iv=1',//品牌名称背景图
                    $brandInfo['name'],//品牌名称
                    $lastQuarterTitle,//季度上榜标题
                    $awardDesc,//季度上榜次数
                    $qrCodeLink,//品牌主页二维码
                    $params['guide_desc'],//二维码旁边的描述
                ];
                break;
        }
        $imageCreateTitle = mBrandHhzCard::TEMPLATE_DESC[$template];
        $imageCreateInfo = mImageCreate::getByWhere([
            'title' => $imageCreateTitle,
            'i_status' => mImageCreate::STATUS_PUBLISH,
        ]);
        if (empty($imageCreateInfo)) {
            throw new \Exception('不存在的模版');
        }
        $createData['tid'] = $imageCreateInfo['id'];
        $createData['size'] = mBrandHhzCard::TEMPLATE_CARD_SIZE[$template];
        if (empty($createData) || empty($createData['tid']) || empty($createData['size']) || empty($createData['params'])) {
            throw new \Exception('生成图片所需参数错误');
        }
        //生成图片
        foreach ($createData['size'] as $key => $row) {
            $buildData['tid'] = $createData['tid'];
            $buildData['params'] = $createData['params'];
            $buildData['width'] = $row['width'];
            $buildData['height'] = $row['height'];
            self::createImg($brandId, $template, $key, $buildData);
        }

        return $result;
    }

    public static function createImg($brandId, $template, $imgKey, $buildData)
    {
        self::_async($brandId, $template, $imgKey, $buildData);
    }

    public static function _async_createImg($brandId, $template, $imgKey, $buildData)
    {
        Log::info('生成品牌名片',
            ['brand_id' => $brandId, 'template' => $template, 'img_key' => $imgKey, 'build_data' => $buildData]);
        $tId = $buildData['tid'];
        $params = $buildData['params'];
        $width = $buildData['width'];
        $height = $buildData['height'];
        $result = ImageCreate::buildImageByTidAndParams($tId, $params, ImageCreate::OP_PIC_MODULE, $width, $height);
        Log::info('生成品牌名片结果', $result);
        $cardInfo = mBrandHhzCard::getInfo(['brand_id' => $brandId, 'template' => $template]);
        if ($cardInfo) {
            $cardImg = $cardInfo['card_img'] ? json_decode($cardInfo['card_img'], true) : [];
            if ($result['code'] && $result['url']) {
                $cardImg[$imgKey] = $result['url'];
                $cardImg = $cardImg ? json_encode($cardImg, JSON_UNESCAPED_UNICODE) : '';
                mBrandHhzCard::updateData(['card_img' => $cardImg], ['brand_id' => $brandId, 'template' => $template]);
            }
        }
    }
}
